package com.anli.leguansuo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: LCG
 * 作者: LCG
 * 日期: 2021/3/9  13:32
 * 描述: 采用定时任务处理 所库存失败的请求
 */
//@Component
public class MyTaskHandler {

    @Autowired
    private LeGuanStockDao leGuanStockDao;

    @Scheduled(cron = "0/1 * * * * ?")
    public void lockHandler(){

        System.out.println("==================运行任务====================");
        List<Map<String, Object>> task = leGuanStockDao.getTask();

        for (Map<String, Object> map : task) {

            Map<String, Object> goodsStock = leGuanStockDao.getGooodsById(map.get("goods_id").toString());
            //if条件成立的话表示库存充足
            if(Long.valueOf(goodsStock.get("stock").toString())>=Integer.valueOf(map.get("quantity").toString())) {
                Map<String, Object> parm = new HashMap<>();
                parm.put("goodsId", map.get("goods_id").toString());
                parm.put("version", goodsStock.get("version"));
                parm.put("stock", Long.valueOf(goodsStock.get("stock").toString()) - Integer.valueOf(map.get("quantity").toString()));

                //更新库存
                int updateStock = leGuanStockDao.updateStock(parm);
                if(updateStock==1){
                    leGuanStockDao.deleteInfo(Long.valueOf(map.get("id").toString()));
                }
            }

        }
    }

}
